var express = require('express');
var router = express.Router();
var login = require("../services/login_service")
var datamodel = require("../services/data_model_service")
var page = require("../services/page_service")
var menu = require("../services/menu_service")
var options = require("../services/options_service")
var tree = require("../services/tree_service")
var onemulti = require("../services/one_multi_service")
var crudbuilder = require("../services/crud_builder_service")
var formbuilder = require("../services/form_builder_service")
var amisbuilder = require("../services/amis_builder_service")
var htmlbuilder = require("../services/html_builder_service")
var configer = require("../services/configer_service")
var report = require("../services/report_service")
var reportbuilder = require("../services/report_builder_service")

let handler = async function (req, res, next) {
	let error = function (status, msg, err) {
		if (err) {
			msg = msg + " 详细错误: " + err.name + " " + err.message;
		}
		err_data = { status: status, msg: msg };
		res.send(err_data);
		console.error(err_data, err);
	}
	let ok = function (result) {
		res.send({ status: 0, msg: "ok", data: result });
	}
	try {
		let service = req.params.service;
		let action = req.params.action;
		let token = req.cookies.token;
		if (service == "login") { // && action=="in"
			let result = await login.handle(action, req.body, {}, req, res);
			if (result instanceof Error) {
				error(500, "登录发生错误", result);
			}
			else {
				ok(result);
			}
		}
		else if (!token) {
			error(403, "未授权的访问 未登录");
			return;
		}
		else {
			let log_info = await login.get_refresh_login_info(token);
			if (log_info instanceof Error) { error(403, "未授权的访问 " + log_info.message); return; }
			console.log("---user info--- "+new Date()+" service:"+service+" action:"+action+" username:" + log_info.username + " user_id:" + log_info.user_id + " emp_id:" + log_info.emp_id + " ip:" + req.ip)
			let result = await eval(service).handle(action, req.body, log_info, req, res);
			if (result instanceof Error) {
				error(500, "调用服务" + service + "发生错误", result);
			}
			else {
				ok(result);
			}
		}
	}
	catch (err) {
		if(err.message=="登录已过期"){
			error(403, "登录已过期", err);
		}
		else{
			error(500, "api出现错误", err);
		}
	}
}
/* API. */
router.all('/:service/:action', handler);

module.exports = router;
